let thunk = ({dispatch, getState}) => next => action => {
  if (typeof action === 'function') {
    return action(dispatch, getState, extraArgument);
  }
  return next(action);
};

function isPromise(val) {
  return val && typeof val.then === 'function';
}

function promiseMiddleware({ dispatch }) {
  return next => action => {
    if (!isFSA(action)) {
      return isPromise(action)
        ? action.then(dispatch)
        : next(action);
    }

    return isPromise(action.payload)
      ? action.payload.then(
        result => dispatch({ ...action, payload: result }),
        error => {
          dispatch({ ...action, payload: error, error: true });
          return Promise.reject(error);
        }
      )
      : next(action);
  };
}
